package library.admin.domain.query;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.util.StringUtils;

/**
 * 
 *
 */
@Data
@ApiModel(description = "分页查询实体")
public class PageQuery {
    @ApiModelProperty("页码")
    private Long pageNo = 1L;
    @ApiModelProperty("分页大小")
    private Long pageSize = 10L;
    @ApiModelProperty("排序字段")
    private String sortBy;
    @ApiModelProperty("是否升序")
    private Boolean isAsc;

    public <T> Page<T> toMpPage(OrderItem... defaultOrderItems) {
        if (defaultOrderItems == null || defaultOrderItems.length == 0) {
            throw new IllegalArgumentException("defaultOrderItems can't be null or empty");
        }
        Page<T> page = new Page<>(pageNo, pageSize);
        if (StringUtils.hasText(sortBy)) {
            if (isAsc == null) {
                throw new IllegalArgumentException("isAsc can't be null");
            }
            page.addOrder(new OrderItem().setColumn(sortBy).setAsc(isAsc));
        } else {
            page.addOrder(defaultOrderItems);
        }
        return page;
    }

    public <T> Page<T> toMpPageDefaultOrderBy(OrderItem defaultOrderItem) {
        return toMpPage(defaultOrderItem);
    }

    public <T> Page<T> toMpPageDefaultOrderByCreateTime() {
        return toMpPageDefaultOrderBy(OrderItem.desc("created_at"));
    }

    public <T> Page<T> toMpPageDefaultOrderByUpdateTime() {
        return toMpPageDefaultOrderBy(OrderItem.desc("updated_at"));
    }
}
